<?php

namespace App\Console\Commands\OpenShop;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Models\OpenShop\InvestmentPromotion\OpenShopContractTemplateModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopMainProcessModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopSignOrderPayHistoryModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopUserContractModel;
use Illuminate\Console\Command;
use Illuminate\Support\Str;
use Kuafu\File\FileUtil;

class AccountCheckDeposit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:account-check-deposit {startTime}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '开店 - 加盟费保证金、装修保证金';

    private array $lists;

    public function handle()
    {
        $startTime = $this->argument('startTime');

        $this->orderNos = [];

        OpenShopSignOrderPayHistoryModel::query()
                                        ->with('mainProcessRel')
                                        ->where('payTime', '>=', strtotime($startTime))
                                        ->where('payStatus', 1)
                                        ->where('sysType', 4)
                                        ->get()
                                        ->each(function ($pay) {

                                            if (isset($this->orderNos[$pay->orderNo])) {
                                                return;
                                            }

                                            $this->orderNos[$pay->orderNo] = 1;

                                            if (!$pay->mainProcessRel) {
                                                return;
                                            }

                                            // 找到所有的关联单
                                            OpenShopMainProcessModel
                                                ::query()
                                                ->where('pid', $pay->mainProcessRel->pid)
                                                ->get()
                                                ->each(function (
                                                    OpenShopMainProcessModel $openShopMainProcessModel
                                                ) {

                                                    $signOrder = $openShopMainProcessModel->signOrderRel;

                                                    if (!$signOrder || $signOrder->payStatus != SignOrderEnum::PAY_STATUS_OK || $signOrder->status == SignOrderEnum::ORDER_STATUS_NO) {
                                                        return;
                                                    }

                                                    $shopCode = $signOrder->shopCode;
                                                    if (isset($this->lists[$shopCode])) {
                                                        return;
                                                    }

                                                    if ($shopCode >= OpenShopSignOrderModel::SHOP_CODE_TEST) {
                                                        return;
                                                    }


                                                    // 合同
                                                    $userContract = OpenShopUserContractModel::query()
                                                                                             ->where('orderNo',
                                                                                                 $openShopMainProcessModel->orderNo)
                                                                                             ->first();

                                                    // 尾款支付时间
                                                    $payHistory = OpenShopSignOrderPayHistoryModel
                                                        ::query()
                                                        ->where('orderNo', $signOrder->orderNo)
                                                        ->where('payStatus', 1)
                                                        ->where('sysType', 4)
                                                        ->when($userContract->mode == OpenShopContractTemplateModel::MODE_3,
                                                            function ($query) use ($signOrder) {
                                                                $query->where('payTime', ">=", $signOrder->signTime);
                                                            })
                                                        ->orderByDesc('id')
                                                        ->first();

                                                    if ($payHistory) {
                                                        $payTime = date('Y-m-d H:i:s', $payHistory->payTime);

                                                        if ($payHistory->payTime < strtotime($startTime)) {
                                                            return;
                                                        }

                                                    } else {
                                                        $payTime = '尾款支付单据未录入系统';
                                                    }

                                                    $this->lists[$shopCode] = [
                                                        $shopCode,
                                                        OpenShopContractTemplateModel::MODE_MAP_TEXT[$userContract->mode] ?? '',
                                                        $userContract->deposit / $userContract->shopCount / 100,
                                                        $userContract->decorationDeposit / $userContract->shopCount / 100,
                                                        $payTime,
                                                    ];

                                                    dump($shopCode);
                                                });


                                        });

        $this->export(['门店编号', '合同类型', '保证金', '装修保证金', '支付时间'], $this->lists);
    }

    /**
     * @param array $headers
     * @param array $data
     * @return void
     */
    public function export(array $headers, array $data)
    {
        // UTF8的BOM头
        $path = sys_get_temp_dir() . '/' . Str::random() . '.csv';
        $fd   = fopen($path, 'w+');
        fwrite($fd, "\xEF\xBB\xBF");

        // 表头
        if ($headers) {
            fputcsv($fd, $headers);
        }

        collect($data)->each(function ($item) use (&$fd) {
            fputcsv($fd, $item);
        });


        if (is_resource($fd)) {
            fclose($fd);
        }

        dump($path);

        $detailUrl = FileUtil::uploadFile($path, 'csv', "tmp/" . date('Ymd') . '/' . Str::uuid() . '.csv')['url'];
        dump($detailUrl);
    }
}
